package com.guide.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.guide.bizdto.AccountSel;
import com.guide.bizdto.CommentsParam;
import com.guide.bizdto.MessageParam;
import com.guide.bizdto.MessageSel;
import com.guide.bizdto.UserInfoParam;
import com.guide.dao.AccountDao;
import com.guide.dao.CommentsDao;
import com.guide.dao.GuideDao;
import com.guide.dao.MessageDao;
import com.guide.dao.MessageTextDao;
import com.guide.dao.TravelTeamDao;
import com.guide.domain.Account;
import com.guide.domain.CommentGuide;
import com.guide.domain.CommentTravel;
import com.guide.domain.Guide;
import com.guide.domain.Message;
import com.guide.domain.MessageText;
import com.guide.domain.TravelTeam;
import com.guide.enums.ErrorCodeEnum;
import com.guide.exception.ServiceException;
import com.guide.service.AccountService;
import com.guide.service.CommentsService;
import com.guide.utils.CommonUtils;
import com.guide.utils.ConstantUtils;

@Service(value="commentsService")
public class CommentsServiceImpl implements CommentsService {
	private static final Logger logger = LoggerFactory
			.getLogger(CommentsServiceImpl.class);
	//private Date nowTime  = new Date();
	@Autowired
	private CommentsDao commentsDao;
	@Autowired
	private GuideDao guideDao;
	@Autowired
	private TravelTeamDao  travelTeamDao;
	@Autowired
	private AccountDao accountDao;
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private MessageTextDao messageTextDao;
	
	@Autowired
	private AccountService accountService;
	
	
	@Override
	public void commentsGuide(CommentsParam commentsParam,Account account) {
		// TODO Auto-generated method stub
		
		CommentGuide commentGuide = commentsDao.getCommentsByTeamIdAndGuideId(Long.valueOf(commentsParam.getTeamId()), Long.valueOf(commentsParam.getGuideId()));
		if(commentGuide!=null){
			throw new ServiceException(ErrorCodeEnum.CODE_COMMENTS_OPT_ERROR);
		}else{
			commentsDao.insertCommentGuide(param2CommentGuide(commentsParam));
			TravelTeam travelTeam = new TravelTeam();
			travelTeam.setId(Long.valueOf(commentsParam.getTeamId()));
			travelTeam.setCommentstatus(ConstantUtils.COMMENT_STATUS_2);
			travelTeam.setMtime(new Date());
			travelTeamDao.updateCommentStatusByPrimaryKeySelective(travelTeam);
		}
	}

	@Override
	@Transactional
	public void commentsTravelorg(CommentsParam commentsParam,Account account) {
		// TODO Auto-generated method stub
		Guide guide = guideDao.getGuideByUserId(account.getUserId());
		commentsParam.setGuideId(String.valueOf(guide.getId()));
		CommentTravel commentTravel = commentsDao.getCommentsByTeamIdAndTravelorgId(Long.valueOf(commentsParam.getTeamId()), Long.valueOf(commentsParam.getGuideId()));
		if(commentTravel!=null){
			throw new ServiceException(ErrorCodeEnum.CODE_COMMENTS_OPT_ERROR);
		}else{
			commentsDao.insertCommentTravel(param2CommentTravel(commentsParam));
			//更新commentstatus的数值
			TravelTeam travelTeam = new TravelTeam();
			travelTeam.setId(Long.valueOf(commentsParam.getTeamId()));
			travelTeam.setCommentstatus(ConstantUtils.COMMENT_STATUS_1);
			travelTeam.setMtime(new Date());
			travelTeamDao.updateCommentStatusByPrimaryKeySelective(travelTeam);
		}
	}

	private CommentGuide param2CommentGuide(CommentsParam commentsParam) {
		CommentGuide commentGuide  = new CommentGuide();
		commentGuide.setTeamId(Long.valueOf(commentsParam.getTeamId()));
		commentGuide.setGuideId(Long.valueOf(commentsParam.getGuideId()));
		commentGuide.setScore(commentsParam.getScore());
		commentGuide.setComments(CommonUtils.unescape(commentsParam.getComments()));
		commentGuide.setCtime(new Date());
		commentGuide.setMtime(new Date());
		return commentGuide;
	}
	private CommentTravel param2CommentTravel(CommentsParam commentsParam) {
		CommentTravel commentTravel = new  CommentTravel();
		commentTravel.setTeamId(Long.valueOf(commentsParam.getTeamId()));
		commentTravel.setGuideId(Long.valueOf(commentsParam.getGuideId()));
		commentTravel.setScore(commentsParam.getScore());
		commentTravel.setComments(CommonUtils.unescape(commentsParam.getComments()));
		commentTravel.setCtime(new Date());
		commentTravel.setMtime(new Date());
		return commentTravel;
	}

	@Override
	public CommentTravel getCommentsTravelByTeamId(Long teamId,Long guideId) {
		// TODO Auto-generated method stub
		//Guide guide = guideDao.getGuideByUserId(account.getUserId());
		return commentsDao.getCommentsByTeamIdAndTravelorgId(teamId, guideId);
	}

	@Override
	public CommentGuide getCommentsGuidelByTeamId(Long teamId,Long guideId) {
		// TODO Auto-generated method stub
		return commentsDao.getCommentsByTeamIdAndGuideId(teamId, guideId);
	}

	@Override
	@Transactional
	public void sendPrivateLetter(MessageParam messageParam,UserInfoParam sendUserInfo,UserInfoParam recUserInfo) {
		
		MessageText messageText = param2Text(messageParam);
		messageTextDao.insertMessageText(messageText);
		Message message = param2Msg(messageParam);
		message.setMsgId(messageText.getId());
		message.setRecId(Long.valueOf(recUserInfo.getUserId()));
		message.setRecname(recUserInfo.getName());
		message.setSendId(Long.valueOf(sendUserInfo.getUserId()));
		message.setSendname(sendUserInfo.getName());
		message.setStatus(ConstantUtils.MSG_READ_0);
		messageDao.insertMessage(message);
	}

	@Override
	public void sendSysLetter(MessageParam messageParam, Account adminAccount) {
		// TODO Auto-generated method stub
		AccountSel sel = new AccountSel();
		sel.setPageIndex(0);
		sel.setPageSize(100000);
		sel.setStatus(ConstantUtils.REGISTER_APPLY_1);
		if(messageParam.getMsgtype()==ConstantUtils.MSG_TYPE_ALL){
			sel.setUserType(null);
		}else if(messageParam.getMsgtype()==ConstantUtils.MSG_TYPE_0) {
			sel.setUserType(ConstantUtils.ACCOUNT_TYPE_0);
		}else if(messageParam.getMsgtype()==ConstantUtils.MSG_TYPE_1) {
			sel.setUserType(ConstantUtils.ACCOUNT_TYPE_1);
		}else if(messageParam.getMsgtype()==ConstantUtils.MSG_TYPE_2) {
			sel.setUserType(ConstantUtils.ACCOUNT_TYPE_2);
		}
		List<Account> accounts = accountDao.getAccountList(sel);
		if(!CollectionUtils.isEmpty(accounts)) {
			MessageText messageText = param2Text(messageParam);
			messageTextDao.insertMessageText(messageText);
			for(Account account:accounts) {
				UserInfoParam userInfoParam = accountService.getAccountDetailByAccount(account);
				Message message = param2Msg(messageParam);
				message.setMsgId(messageText.getId());
				message.setRecId(Long.valueOf(userInfoParam.getUserId()));
				message.setRecname(userInfoParam.getName());
				message.setSendId(Long.valueOf(adminAccount.getUserId()));
				message.setSendname("管理员");
				message.setStatus(ConstantUtils.MSG_READ_0);
				messageDao.insertMessage(message);
			}
			Message message1 = new Message();
			message1.setSendId(Long.valueOf(adminAccount.getUserId()));
			message1.setSendname("管理员");
			message1.setRecId(-1L);
			message1.setPmsgId(-1L);
			message1.setMsgId(messageText.getId());
			message1.setMsgtype(messageParam.getMsgtype());
			message1.setCtime(new Date());
			message1.setMtime(new Date());
			message1.setStatus(ConstantUtils.MSG_READ_0);
			messageDao.insertMessage(message1);
		}
	}
	
	
	private MessageText param2Text(MessageParam messageParam){
		MessageText messageText =  new MessageText();
		messageText.setSubject(messageParam.getSubject());
		messageText.setMessage(CommonUtils.unescape(messageParam.getMessage()));
		messageText.setCtime(new Date());
		return messageText;
	}
	private Message param2Msg(MessageParam messageParam){
		Message message = new Message();
		message.setSendId(null);
		message.setRecId(null);
		message.setPmsgId(StringUtils.isEmpty(messageParam.getPmsgId())?-1:Long.valueOf(messageParam.getPmsgId()));
		message.setMsgId(null);
		message.setMsgtype(messageParam.getMsgtype());
		message.setCtime(new Date());
		message.setMtime(new Date());
		message.setStatus(messageParam.getStatus());
		return message;
	}

	@Override
	public Map<String, Object> getLetters(MessageSel messageSel,Account account) {
		List<Message> messageList = messageDao.getMessageByPage(account.getUserId(), messageSel.getPageIndex(), messageSel.getPageSize());
		
		Integer countTotal = messageDao.counrMessageByUserId(account.getUserId());
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put(ConstantUtils.DATE_LIST, message2ParamList(messageList));
		retMap.put(ConstantUtils.TOTAL_COUNT, countTotal);
		return retMap;
	}
	
	@Override
	public Map<String, Object> getLettersSys(MessageSel messageSel,
			Account account) {
		List<Message> messageList = messageDao.getMessageSysByPage(messageSel.getMsgType(), messageSel.getPageIndex(), messageSel.getPageSize());
		
		Integer countTotal = messageDao.countMessageSysByUserId(messageSel.getMsgType());
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put(ConstantUtils.DATE_LIST, message2ParamList(messageList));
		retMap.put(ConstantUtils.TOTAL_COUNT, countTotal);
		return retMap;
	}
	
	private List<MessageParam>  message2ParamList(List<Message> messageList){
		List<MessageParam> MessageParams = new ArrayList<MessageParam>();
		if(!CollectionUtils.isEmpty(messageList)) {
			for(Message message:messageList) {
				MessageParams.add(message2Param(message));
			}
		}
		return MessageParams;
	}
	
	private MessageParam  message2Param(Message message){
		MessageParam messageParam = new MessageParam();
		messageParam.setId(String.valueOf(message.getId()));
		messageParam.setRecId(String.valueOf(message.getRecId()));
		//messageParam.setRecUserName(account.getUserName());
		messageParam.setRecName(message.getRecname());
		messageParam.setSendId(String.valueOf(message.getSendId()));
		messageParam.setSendName(message.getSendname());
		MessageText messageText = messageTextDao.getMessageTextById(message.getMsgId());
		if(messageText!=null){
			messageParam.setSubject(messageText.getSubject());
			messageParam.setMessage(messageText.getMessage());
		}
		messageParam.setMsgtype(message.getMsgtype());
		messageParam.setMsgId(String.valueOf(message.getMsgId()));
		messageParam.setCtime(CommonUtils.DateToStr(message.getCtime(), "yyyy-MM-dd HH:mm"));
		messageParam.setStatus(message.getStatus());
		messageParam.setPmsgId(String.valueOf(message.getPmsgId()));
		return messageParam;
	}

	@Override
	public MessageParam getLetterById(Long messageId) {
		// TODO Auto-generated method stub
		Message message = messageDao.getMessageById(messageId);
		return message2Param(message);
	}

	@Override
	public void markRead(Long messageId) {
		// TODO Auto-generated method stub
		Message message = new Message();
		message.setId(messageId);
		message.setStatus(ConstantUtils.MSG_READ_1);
		message.setMtime(new Date());
		messageDao.markRead(message);
	}

	@Override
	public Integer getUnreadLetterCount(Long userId,Integer status) {
		// TODO Auto-generated method stub
		return messageDao.getUnreadLetterCount(userId, status);
	}


	
	
	
}
